//var service = angular.module('starter.services', []);
service.factory('missionFactory',['$q',function($q){

    var ORDER_FIELDS = ['remark','payway','uid','address','messioned','orderid','total','paytime','approvaldate','type','finalAmount','description','areaId','shopId','status','goods','location'];
    var ORDER_TYPE = {retrunGoods:11,exchangeGoods:12};
    var Mission = AV.Object.extend('Mission');
    var CourierCart = AV.Object.extend('CourierCart');
    var Product = AV.Object.extend('Product');
    var Order = AV.Object.extend('Order');

    //售后订单的类型;
    var RETURN_ORDER_TYPE = [11,12];
    //列表需要的状态码
    var ORDER_STATUS = [2500,3000,4000];

    //售后订单列表需要的状态码
    var RETURNORDER_STATUS = [3000,4000];

    var get0Time = function(){
        var today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        today.setMilliseconds(0);
        return today.getTime()/1000;
    }
    return {
        PAGE_SIZE:20,
        getMissionInfo:function(page){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Mission);
            queryMission.skip(this.PAGE_SIZE * (page - 1));
            queryMission.equalTo('uid',uid+'');
            queryMission.equalTo('status',1);
            queryMission.descending('updatedAt');
            queryMission.limit(this.PAGE_SIZE);
            return queryMission.find();
        },
        /**
         * 获取任务列表 直连order表
         * @param page
         * @param orders
         * @returns {*|AV.Promise}
         * auth:nico
         * 2016-01-10
         */
        getMissionInfoGroupByOrderStatus:function(page,orders){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Order);
            queryMission.skip(this.PAGE_SIZE * (page - 1));
            queryMission.equalTo('messionedUser',uid+'');
            queryMission.descending('updatedAt');
            queryMission.notContainedIn('type',[11,12]);
            if(orders.type === "mhcx"){
                queryMission.contains('orderid',orders.orderid);
            }
            if(orders.type === "afljMISSIOIN"){
                //queryMission.equalTo("status",parseInt(orders.status));  //"status",orders.status
                queryMission.containedIn("status",[7000,8000]);
            }
            queryMission.limit(this.PAGE_SIZE);

            return queryMission.find();
        },
        /**
         * 手动查询订单
         * @param page
         * @param orderid
         * @returns {*|AV.Promise}
         */
        searchMissionByHand:function(page,orderid){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Order);
            queryMission.skip(this.PAGE_SIZE * (page - 1));
            queryMission.equalTo('messionedUser',uid+'');
            queryMission.descending('updatedAt');
            //queryMission.notContainedIn('type',[11,12]);
            queryMission.contains('orderid',orderid);
            queryMission.limit(this.PAGE_SIZE);
            return queryMission.find();
        },
        /**
         * 获取手动查询任务的总记录数
         * @param orderid
         * @returns {*|AV.Promise}
         */
        searchMissionByHandCount:function(orderid){
            //messionedUser = ? & status = [2500,3000,4000]
            var storage = window.localStorage;
            var uid = storage.getItem("uid")
            var queryMission = new AV.Query(Order);
            queryMission.equalTo('messionedUser',uid+'');
            queryMission.contains('orderid',orderid);
            return queryMission.count();
        },
        searchMissions:function(orderid){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Mission);
            queryMission.equalTo('uid',uid+'');
            queryMission.equalTo('status',1);
            queryMission.descending('updatedAt');
            queryMission.contains('orderid',orderid);
            return queryMission.find();
        },
        getOrderInfo:function(orderid){
            var queryOrder = new AV.Query(Order);
            queryOrder.equalTo('orderid',orderid);
            return queryOrder.first();
        },
        getMissionCount:function(){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Mission);
            queryMission.equalTo('uid',uid+'');
            queryMission.equalTo('status',1);
            return queryMission.count();
        },
        insertCourier:function(list){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");

            var queryCourier = new AV.Query(CourierCart);
            queryCourier.equalTo('uid',uid+'');
            queryCourier.equalTo('pid',list.pid+'');
            queryCourier.equalTo('psid',list.psid+'');
            queryCourier.first().then(function(res){
                if(res){
                    var oldNum = res.get('num');
                    var newNum = list.num ;
                    res.save({num:parseInt(oldNum+(parseInt(newNum)-parseInt(oldNum)))}).then(function(data){
                        q.resolve({code:0,data:data});
                    }).catch(function(err){
                        q.reject({code:1});
                    });
                }else{
                    q.reject({code:1});
                }
            });
            return q.promise;
        },
        getAllCountByStatus:function(){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var query = new AV.Query(Mission);
            query.equalTo('uid',uid+'');
            query.equalTo('status',1);
            return query.count();
        },
        /**
         * 根据状态获取订单数量
         * @param MISSION_TYPE
         * @param MISSION_TYPE_NAME
         * @returns {*}
         * auth：nico
         * 2016-01-29
         */
        getCountByStatus:function(MISSION_TYPE,MISSION_TYPE_NAME){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            async.auto({
                countByStatus:function(callback){
                    var returnData=[];
                    var query = new AV.Query(Order);
                    query.equalTo('messionedUser',uid+'');
                    async.eachOfSeries(MISSION_TYPE,function(value,keys,callback1){
                        query.notContainedIn('type',[11,12]);
                        query.equalTo('status',parseInt(value));
                        query.count().then(function(count){
                            returnData.push({type:keys,name:MISSION_TYPE_NAME[keys],count:count});
                            console.log(returnData);
                            callback1(null,returnData );
                        });
                    },function(err){
                        if(err){
                            callback(null, {code:-1,returnData:returnData});
                        }else{
                            callback(null, {code:0,returnData:returnData});
                        }
                    });
                },
                countByType:function(callback){
                    var returnData1=[];
                    var query = new AV.Query(Order);
                    query.equalTo('messionedUser',uid+'');
                    async.eachSeries([11,12],function(value,callback1){
                        var status = [7000,8000];
                        query.containedIn('status',status);
                        query.equalTo('type',value);
                        query.count().then(function(count){
                            returnData1.push({count:count});
                            callback1(null,returnData1 );
                        });
                    },function(err){
                        if(err){
                            callback(null, {code:-1,returnData:returnData1});
                        }else{
                            callback(null, {code:0,returnData:returnData1});
                        }
                    });
                },
                final:['countByStatus','countByType',function(callback,results){

                    callback(null, {code:0,countByStatus:results.countByStatus.returnData,countByType:results.countByType.returnData})
                }]
            },function(err,results){
                if(err){
                    q.reject(err);
                }else{
                    console.log(results.final);
                    q.resolve(results.final);
                }
            });
            return q.promise;
        },
        /**
         * 获取售后订单列表
         * @param type
         * @param uid
         * @param page
         * @param typeName
         * @returns {*|AV.Promise}
         */
        getSalesOrder:function(type,uid,page,typeName){
            var queryOrder = new AV.Query(Order);
            var status = [7000,8000];
            queryOrder.skip(this.PAGE_SIZE * (page - 1));
            queryOrder.select(ORDER_FIELDS);
            queryOrder.equalTo('type',parseInt(type));
            queryOrder.containedIn('status',status);
            queryOrder.equalTo('messionedUser',uid+"");
            queryOrder.limit(this.PAGE_SIZE);
            return queryOrder.find();
        },
        getCountOfSales:function(type,uid,typeName){
            var queryOrder = new AV.Query(Order);
            var status = [7000,8000];
            queryOrder.select(ORDER_FIELDS);
            queryOrder.equalTo('type',parseInt(type));
            queryOrder.containedIn('status',status);
            queryOrder.equalTo('messionedUser',uid+"");
            return queryOrder.count();
        },
        getCountInMission:function(options){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            async.auto({
                //获取退货数量
                getTHCount:function(callback){
                    var queryOrder = new AV.Query(Order);
                    var status = [7000,8000];
                    queryOrder.select(ORDER_FIELDS);
                    queryOrder.equalTo('type',ORDER_TYPE.retrunGoods);
                    queryOrder.containedIn('status',status);
                    queryOrder.equalTo('messionedUser',uid+"");
                    queryOrder.count().then(function(count){
                        callback(null,count);
                    }).catch(function(err){
                        callback(null,0);
                    });
                },
                //获取换货数量
                getHHCount:function(callback){
                    var queryOrder = new AV.Query(Order);
                    var status = [7000,8000];
                    queryOrder.select(ORDER_FIELDS);
                    queryOrder.equalTo('type',ORDER_TYPE.exchangeGoods);
                    queryOrder.containedIn('status',status);
                    queryOrder.equalTo('messionedUser',uid+"");
                    queryOrder.count().then(function(count){
                        callback(null,count);
                    }).catch(function(err){
                        callback(null,0);
                    });
                },
                //获取订单池子数量
                getCZCount:function(callback){
                    var todayZeroTime = get0Time();
                    var tomZeroTime = todayZeroTime + 60 * 60 * 24;

                    var myOrder = new AV.Query(Order);
                    myOrder.select(ORDER_FIELDS);
                    myOrder.containedIn('status',RETURNORDER_STATUS);
                    myOrder.containedIn('type',RETURN_ORDER_TYPE);
                    myOrder.containedIn('areaId',options.areaId);
                    myOrder.notEqualTo('messioned',true);
                    myOrder.addDescending('status');
                    myOrder.addAscending('paytime');

                    var normalOrder = new AV.Query(Order);
                    normalOrder.select(ORDER_FIELDS);
                    normalOrder.containedIn('status',RETURNORDER_STATUS);
                    normalOrder.containedIn('type',RETURN_ORDER_TYPE);
                    normalOrder.containedIn('areaId',options.areaId);
                    normalOrder.notEqualTo('messioned',true);
                    normalOrder.addDescending('status');
                    normalOrder.addAscending('paytime');

                    var monthOrder = new AV.Query(Order);
                    monthOrder.select(ORDER_FIELDS);
                    monthOrder.containedIn('status',RETURNORDER_STATUS);
                    monthOrder.containedIn('type',RETURN_ORDER_TYPE);
                    monthOrder.lessThan('bookdate',''+tomZeroTime);//小于第二天
                    monthOrder.greaterThan('bookdate',''+todayZeroTime);//大于凌晨
                    monthOrder.containedIn('areaId',options.areaId);
                    monthOrder.notEqualTo('messioned',true);
                    monthOrder.addDescending('status');
                    monthOrder.addAscending('paytime');

                    var query = AV.Query.or(myOrder,normalOrder, monthOrder);
                    query.count().then(function(count){
                        callback(null,count);
                    }).catch(function(err){
                        callback(null,0);
                    });
                }
            },function(err,results){
                if(err){
                    q.reject({returnGoodsCount:results.getTHCount,exchangeGoodsCount:results.getHHCount,chiziCount:results.getCZCount});
                }else{
                    q.resolve({returnGoodsCount:results.getTHCount,exchangeGoodsCount:results.getHHCount,chiziCount:results.getCZCount});
                }
            });
            return q.promise;
        },
        /**
         *从order表中获取任务总数:直接从order表中获取某些内容
         * 非售后订单
         * @param status
         * @returns {*|AV.Promise}
         * auth:nico
         * 2016-01-10
         */
        getMissionCountFromOrder:function(status){
            //messionedUser = ? & status = [2500,3000,4000]
            var storage = window.localStorage;
            var uid = storage.getItem("uid")
            var queryMission = new AV.Query(Order);
            queryMission.equalTo('messionedUser',uid+'');
            queryMission.notContainedIn('type',[11,12]); //排除退换货订单
            queryMission.containedIn('status',status);
            return queryMission.count();
        },

        /**
         * 从order表中获取任务列表
         * @param orderid
         * @returns {*|AV.Promise}
         * auth:nico
         * 2016-01-10
         */
        searchMissionFormOrder:function(orderid){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Order);
            var ORDER_STATUS = [7000,8000];
            queryMission.containedIn('status',ORDER_STATUS);
            queryMission.equalTo('messionedUser',uid+'');
            queryMission.descending('updatedAt');
            queryMission.contains('orderid',orderid);
            return queryMission.find();
        },
        //
        /**
         * 更新order表的updatedAt字段，用于排序，优先级
         * @param orderid
         * @returns {*}
         * auth:nico
         * 2016-01-10
         */
        updateMissionUpdatedAtOrder:function(orderid){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var query = new AV.Query(Order);
            query.equalTo('orderid',orderid+'');
            query.equalTo('messionedUser',uid+'');
            query.first().then(function(data){
                if(data){
                    data.save({updatedAt:new Date()}).then(function(){
                        q.resolve({code:0})
                    }).catch(function(err){
                        q.reject({code:-1});
                    });
                }else{
                    q.reject({code:-1});
                }
            });
            return q.promise;
        },

        //showMissionDetails
        /**
         * 展示任务详情
         * @param orderid
         * @returns {*}
         * auth:nico
         * 2016-01-10
         */
        showMissionDetails:function(orderid){
            var q = $q.defer();
            var query = new AV.Query(Order);
            var uid = storage.getItem("uid");
            var area = JSON.parse(storage.getItem("globalArea"));
            var shopArea = JSON.parse(storage.getItem("shopArea"));
            var button_show = {inDispatching:0,dispatchingSuccessful:0};
            var goodsShop = '' ;
            query.equalTo('orderid',orderid+'');
            query.first().then(function(data){
                if(data){
                    if(data.get('status') === 7000){
                        button_show.inDispatching = 1;
                    }
                    if(data.get('status') >= 8000){
                        button_show.inDispatching = 0;
                        button_show.dispatchingSuccessful = 1;
                    }
                    if([6,7,8].indexOf(data.get('type')) >=0){
                        //外卖商品显示果饮店
                        goodsShop = shopArea[data.get('shopId')]
                    }else{
                        //普通商品，显示分区
                        goodsShop = area[data.get('areaId')]
                    }
                    q.resolve({code:0,button_show:button_show,data:{orderid:orderid,orderInfo:data,address:data.get('address'),goods:data.get('goods'),area:area[data.get('areaId')] ,shop:goodsShop,bookdate:data.get('bookdate')}});

                }else{
                    alert('error');
                    q.reject({code:1,button_show:button_show,data:{orderid:"",orderInfo:{},address:{},goods:{},area:{},shop:{},bookdate:new Date()}});
                }
            });
            return q.promise;
        },

        /**
         * 开始派送
         * @param orderid
         * @returns {*}
         * auth:nico
         * 2016-01-10
         */
        dispatching:function(orderid){
            var q = $q.defer();
            async.auto({
                getOrderInfo:function(callback){
                    var queryOrder = new AV.Query(Order);
                    queryOrder.equalTo('orderid',orderid);
                    queryOrder.first().then(function(data){
                        callback(null, data);
                    }).catch(function(err){
                        callback(err);
                    });
                },
                changeOrderInfo:['getOrderInfo',function(callback,results){
                    var orderInfo = results.getOrderInfo ;
                    if(orderInfo){
                        //变更状态
                        if(orderInfo.get('status')===7000){
                            orderInfo.set('status',8000);
                            //向订单表中插入任务流水中的开始时间---开始
                            orderInfo.set('startTime',new Date());
                            //向订单表中插入任务流水中的开始时间---结束
                            orderInfo.save().then(function(){
                                console.log("变更成功");
                                callback(null,{code:0,msg:'变更成功'});
                            });
                        }else{
                            callback({code:1,msg:'核对状态！'});
                        }
                    }else{
                        return ;
                    }
                }],
                finalFunction:["changeOrderInfo",function(callback,results){
                    if(results.changeOrderInfo.code === 0){
                        //更新成功
                        var phone = results.getOrderInfo.get('address').phone;
                        var uName = results.getOrderInfo.get('address').name
                        AV.Cloud.requestSmsCode({
                            mobilePhoneNumber: phone,
                            template: "配送通知",
                            orderid:orderid,
                            name: '果然100',
                            uName:uName
                        }).then(function(data){
                            //发送成功
                            callback(null, {code:0,msg:'发送成功'});
                        }, function(err){
                            //发送失败
                            console.log(err);
                            callback(null, {code:1,msg:'发送失败'});
                        });
                        callback(null, {code:0,msg:'发送成功'});
                    }else{
                        callback(null, {code:1,msg:'更新失败，短信发送失败'});
                    }
                }]

            },function(err,results){
                if(err){
                    q.reject(err);
                }else{
                    q.resolve(results.finalFunction);
                }
            });
            return q.promise;
        },
        /**
         * 完成派送时保存方法
         * @param orderid
         * @param realtotal
         * @param remark
         * @returns {*}
         * auth:nico
         * 2016-01-10
         */
        completeDispatching:function(orderid,realtotal,remark){
            var q = $q.defer();
            async.waterfall([
                //更新order表
                function(callback) {
                    //console.log(111111);
                    var queryOrder = new AV.Query(Order);
                    queryOrder.equalTo('orderid', orderid);
                    queryOrder.first().then(function (data) {
                        if (data) {
                            data.set('status', 9000);
                            //向订单表中插入任务流水中的数据---开始
                            data.set('endTime',new Date());
                            data.set('realAccount', realtotal+'');
                            data.set('psremark', remark);
                            //向订单表中插入任务流水中的数据---结束
                            data.set('syncStatus', 2);
                            data.save().then(function () {
                                callback(null, {code: 0, orderInfo: data});
                            }).catch(function (err) {
                                callback(err);
                            });
                        } else {
                            callback(null, {code: 1, orderInfo: data});
                        }
                    });
                }
            ], function (err, result) {
                if (err) {
                    q.reject(err);
                }else{
                    q.resolve(result);
                }
            });
            return q.promise;
        },
        /**
         * 取消派送
         * @param orderid
         * @returns {*}
         * auth:nico
         * 2016-01-10
         */
        cancelDispatching:function(orderid,cancelReason){
            //取消派送，只修改状态为7000
            var q = $q.defer();
            var query = new AV.Query(Order);
            var uid = storage.getItem("uid");
            var area = JSON.parse(storage.getItem("globalArea"));
            var shopArea = JSON.parse(storage.getItem("shopArea"));
            var goodsShop = '' ;
            query.equalTo('orderid',orderid+'');
            query.first().then(function(data){
                if(data){
                    data.set('status',7000) ;
                    data.set('cancelReason',cancelReason);
                    data.set('canceledAt',new Date());
                    data.save().then(function(){
                        q.resolve({code:0,msg:'取消成功'});
                    }).catch(function(){
                        q.reject({code:-1,msg:'取消失败'});
                    });
                }else{
                    q.reject({code:-1,msg:'订单号不存在，请联系客服'});
                }
            });
            return q.promise;
        }

    }

}]);